package com.choosefine.it.worker.service.Impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.choosefine.it.basedata.service.CountService;
import com.choosefine.it.company.model.CompanyPublishproject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.dao.ProjectInfoMapper;
import com.choosefine.it.basedata.dao.WorkTypeMapper;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.json.JsonResult;
import com.choosefine.it.common.utils.IdsUtil;
import com.choosefine.it.team.dao.ItemInfoMapper;
import com.choosefine.it.team.model.TeamPublishFindWorkerInfo;
import com.choosefine.it.team.service.TeamPublishFindWorkerInfoService;
import com.choosefine.it.worker.dao.MyWorksManagerMapper;
import com.choosefine.it.worker.dao.WorkerWorkTypeMapper;
import com.choosefine.it.worker.model.WorkDetailInfo;
import com.choosefine.it.worker.model.WorkerFavoriteWork;
import com.choosefine.it.worker.model.WorkerHistoryInfo;
import com.choosefine.it.worker.model.WorkerItemsRelation;
import com.choosefine.it.worker.service.MyWorksManagerService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

/**
 * 工人工作相关 实现 （收到评论、收藏、工作过的历史）
 * 
 * @auth liaozhanggen 2016-11-18 下午4:28:46
 *
 */
@SuppressWarnings("rawtypes")
@Service("myWorksManagerService")
public class MyWorksManagerServiceImpl implements MyWorksManagerService {
	private Logger logger = LoggerFactory.getLogger(MyWorksManagerServiceImpl.class);
	
	final JsonResult result = new JsonResult();
	@Autowired
	MyWorksManagerMapper myWorksManagerMapper;
	@Autowired
	ProjectInfoMapper projectInfoMapper;
	@Autowired
	ItemInfoMapper itemInfoMapper;
	@Autowired
	MongoTemplate mongoTemplate;
	@Autowired
	WorkTypeMapper workTypeMapper;
	@Autowired
	WorkerWorkTypeMapper workerWorkTypeMapper;
	@Autowired
	TeamPublishFindWorkerInfoService teamPublishFindWorkerInfoService;
	@Autowired
	CountService countService;

		

	private void checkData(WorkerItemsRelation wir) throws BusinessException {
		//校验传递的字段值有效性
		if (StringUtils.isEmpty(wir.getUserCode())) {
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, CommonConstant.WORKER_USERINFO_USERID_IS_NULL);
		}
		if (StringUtils.isEmpty(wir.getProjectCode()) 
				|| null == wir.getTeamId() 
				|| 0 == wir.getTeamId().intValue()
				||StringUtils.isEmpty(wir.getWorkerTypeIdes())) {
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, CommonConstant.TEAM_RECRUITMENT_ID_IS_NULL);
		}
	}

	private void checkData(String userCode) throws BusinessException {
		if (StringUtils.isEmpty(userCode)) {
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, CommonConstant.WORKER_USERINFO_USERID_IS_NULL);
		}
	}
	
//	@Override
//	public Page<WorksAppraise> queryWorkComment(UserInfo user, PageDTO pageDTO) throws BusinessException {
//		
//		//根据分页查询 某区间的数据集
//		Map<String, Object> param = MapUtil.transBean2Map(pageDTO);
//		param.put(CommonConstant.USER_CODE, user.getUserCode());
//		
//		//分页
//		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
//		Page<WorksAppraise> pageInfo= myWorksManagerMapper.queryWorkComment(param);
//		return pageInfo;
//	}

	


	@Override
	public Page<WorkerFavoriteWork> queryMyFavoriteTeamRecruitmentWorkPageByUuid(Map map,PageDTO pageDTO) throws BusinessException {
		checkData((String) map.get("userCode"));
		//组装当前页码信息
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<WorkerFavoriteWork> page = myWorksManagerMapper.queryFavoriteWork(map);
		return page;
	}

	@Override
	public int insertFavoriteWork(Map<String, Object> param) throws BusinessException {
		int num=0;
		int isInsert=countService.isInsert(param);
		if(0==isInsert){
		 num=myWorksManagerMapper.insertFavoriteWork(param);
		 	int favoriteCount=countService.favoriteCount(param);
			Update update=new Update();
			update.set("favoriteCount",favoriteCount);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(param.get("publishId"))),update,TeamPublishFindWorkerInfo.class);
		}
		return num;
	}

	@Override
	public int modifyFavoriteWorkStatus(Map<String, Object> param) throws BusinessException {
		int num=0;
		int isInsert=countService.isInsert(param);
		if(isInsert>0){
			num=myWorksManagerMapper.modifyFavoriteWorkStatus(param);
			int favoriteCount=countService.favoriteCount(param);
			Update update=new Update();
			update.set("favoriteCount",favoriteCount);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(param.get("publishId"))),update,TeamPublishFindWorkerInfo.class);
		}
		return num;
	}

	@Override
	public int addBatchWorkerItemsRelation(List<WorkerItemsRelation> wItemsRelations) throws BusinessException {
		for (WorkerItemsRelation wir : wItemsRelations) {
			checkData(wir);
			wir.setCtime(System.currentTimeMillis());
		}
		
		int num = myWorksManagerMapper.addBatchWorkerItemsRelation(wItemsRelations);
		if (num > 0) {
			//为便于后续的读取速度及依赖的查询关系，顾先存储于Mongodb中
			for (WorkerItemsRelation wir : wItemsRelations) {
				//保存工人工种
//				List<WorkerAndWorkTypeDTO> list = saveWorkerWorkType(wir);
				List<Integer> list = IdsUtil.getIds(wir.getWorkerTypeIdes());
				Map<String, Object> paras=new HashMap<>();
				paras.put("workTypeIdes", list);
				paras.put("workerItemsRelationId", wir.getId());
				workerWorkTypeMapper.saveWorkerWorkType(paras);
				
				logger.info("-----WorkerItemsRelation.id--->" + wir.getId());
				
				//读取项目信息
				wir.setProjectInfo(projectInfoMapper.queryProjectInfoByCode(wir.getProjectCode()));
				//读取班组信息
				wir.setItemInfo(itemInfoMapper.findItemInfoById(wir.getTeamId()));
				//工种类型
//				wir.setWorkType(workTypeMapper.findWorkTypeById(wir.getWorkTypeId()));
				
				wir.setWorkTypeList(workTypeMapper.findWorkTypeListByIdes(paras));
			}
			
			//Mongodb存储起来
			mongoTemplate.insert(wItemsRelations, WorkerItemsRelation.class);
		}
		return num;
	}
	
//	private List<WorkerAndWorkTypeDTO> saveWorkerWorkType(WorkerItemsRelation wir){
//		//保存工人工种
//		String typeIdes = wir.getWorkerTypeIdes();
//		String[] idse = null;
//		List<WorkerAndWorkTypeDTO> list = new ArrayList<>();
//		if(typeIdes.contains(",")){
//			idse=typeIdes.split(",");
//			for (String id : idse) {
//				WorkerAndWorkTypeDTO workerAndWorkTypeDTO = new WorkerAndWorkTypeDTO();
//				workerAndWorkTypeDTO.setWorkerTeamId(wir.getId());
//				workerAndWorkTypeDTO.setWorkTypeId(Integer.parseInt(id));
//				list.add(workerAndWorkTypeDTO);
//			}
//		}else{
//			WorkerAndWorkTypeDTO workerAndWorkTypeDTO = new WorkerAndWorkTypeDTO();
//			workerAndWorkTypeDTO.setWorkerTeamId(wir.getId());
//			workerAndWorkTypeDTO.setWorkTypeId(Integer.parseInt(typeIdes));
//			list.add(workerAndWorkTypeDTO);
//		}
//		
//		return list;
//	}

	@Override
	public Page<WorkerItemsRelation> queryWorkerItemsRelationPageByUCode(String userCode, PageDTO page) throws BusinessException {
		checkData(userCode);
		//读取与当前人关联的工作列表 - 主键
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		Page<WorkerItemsRelation> wirs = myWorksManagerMapper.queryWorkerItemsRelationPageByUCode(userCode);

		for (int index = 0; index < wirs.size(); index++) {

			WorkerItemsRelation wr = mongoTemplate.findOne(new Query(Criteria.where("_id").is(wirs.get(index).getId())), WorkerItemsRelation.class);
			wr.setTotalReceivable(wirs.get(index).getTotalReceivable());
			wr.setTotalReceived(wirs.get(index).getTotalReceived());
			wr.setTotalUnpaid(wirs.get(index).getTotalReceivable().subtract(wirs.get(index).getTotalReceived()));
			//如果存在，则读取Mongodb中的数据
			wirs.set(index,wr );
		}
		return wirs;
	}

	@Override
	public Page<WorkerHistoryInfo> queryWorkerHistoryWorkInfo(String userCode,PageDTO page) {
		String msg = null;
		Map<String, Object> param = null;
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		Page<WorkerHistoryInfo> historyInfos = myWorksManagerMapper.queryWorkerHistoryWorkInfo(userCode);
		
		for (WorkerHistoryInfo whi : historyInfos) {
			param = new HashMap<String, Object>();
			param.put("userCode", whi.getUserCode());
			param.put("workItemsRelationId", whi.getWorkerTeamRelationId()+"");
			param.put("startWorkTime", "0");
			param.put("endWorkTime", "0");
			param.put("workTotalHour", "0");
			
			//统计出员工进入班组的入职时间、完工时间、总工时
			msg = myWorksManagerMapper.countWorkAttendanceCurrentMonthCalc(param);
			if(null != param.get("startWorkTime"))
			whi.setStartWorkTime(Long.valueOf(null == param.get("startWorkTime") ? "0" : param.get("startWorkTime").toString()).longValue());
			whi.setEndWorkTime(Long.valueOf(null == param.get("endWorkTime") ? "0" : param.get("endWorkTime").toString()).longValue());
			whi.setTotalWorkHour(Integer.valueOf(null == param.get("workTotalHour") ? "0" : param.get("workTotalHour").toString()));
			msg = null;
			param = null;
		}
		return historyInfos;
	}
	
	/**
	 * 查询工人所在班组的工作详情（班组、工程、月考勤信息）
	 * 
	 * @auth liaozhanggen 2016-12-2 上午11:42:31
	 */
	@Override
	public WorkDetailInfo queryWorkerWorkDetialInfo(String userCode,Integer relationId) throws BusinessException {
		WorkDetailInfo workDetailInfo=myWorksManagerMapper.queryWorkerWorkDetialInfo(userCode,relationId);
		if(workDetailInfo!=null){
		workDetailInfo.setTotalUnpaid(workDetailInfo.getTotalReceivable().subtract(workDetailInfo.getTotalReceived()));
		}
		return workDetailInfo;
	}

//	@Override
//	public int addWorkComment(WorkerCommentDTO workerCollectionDTO) throws BusinessException {
//		return myWorksManagerMapper.insertWorkComment(workerCollectionDTO);
//	}

	/**
	 *
	 * 
	 * @author liaozhanggen 2017年2月20日
	 * @throws BusinessException 
	 */
	@Override/*yuxin*/
	public TeamPublishFindWorkerInfo findTeamRecruitmentInfoById(Map map) throws BusinessException {
		TeamPublishFindWorkerInfo trInfo=mongoTemplate.findOne(new Query(Criteria.where("_id").is(map.get("publishId"))),TeamPublishFindWorkerInfo.class);
		if(trInfo!=null){
		int isInsert=countService.isInsert(map);
		trInfo.setIsInsert(isInsert);
		}
		return trInfo;
	}
}